<template>
    <van-image
      width="100%"
      height="500"
      fit="cover"
      :src="product.thumbs_text"
    />

    <div class="detailbox">
      <h4>{{product.name}}</h4>
      <div class="price">
        单独购买：<em>￥</em>{{product.price}} 
        <!-- 拼团价格：<em>￥</em>50 -->
      </div>
    </div>
    
    <div class="allkbox"></div>
    
    <!-- 商品规格 -->
    <div class="info_choice">
      <!-- Sku 商品规格 -->
      <div class="commodity" @click="SkuShow = true">
        <div class="opt">
          <div class="title wanl-gray">选择</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>尺码</span>
                <span>颜色</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
      <!-- 服务 -->
      <div class="commodity" @click="TipShow = true">
        <div class="opt">
          <div class="title wanl-gray">服务</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>7天无理由退款</span>
                <span>·</span>
                <span>24小时内发货</span>
                <span>·</span>
                <span>假一赔十</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
    </div>

    <div class="allkbox"></div>

    <!-- 选项卡 -->
    <van-tabs v-model:active="TabActive" type="card" color="#EE0A24" sticky class="card">
      <van-tab title="产品参数">
        <div style="text-align: center;" v-html="product.content"></div>
      </van-tab>
      <van-tab title="商品评价">
        <div class="rate" style="overflow-x: hidden;">
          <div class="rate-header" v-if="product.rate!=-1">
            <div class="rate-score">
              <h4>与描述相符</h4>
              <strong>{{product.rate}}</strong>
            </div>
            <div class="rate-graph">
              <van-rate v-model="product.rate" allow-half readonly />
            </div>
          </div>
          <div class="rate-content" v-if="product.rate==-1">
            <div class="rate-empty">该商品还没有人写评价呢</div>
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <van-pull-refresh v-model="refreshing" @refresh="refresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :offset="10"
        :immediate-check="false"
        finished-text="没有更多了"
        v-model:error="error"
        error-text="请求失败，点击重新加载"
        @load="load"
      >
        <ul class="proul">
          <li v-for="comment in commentList" :key="comment.id">
            <div class="rate-content">
              <div>
                <div class="review-box">
                  <div class="review-item">
                    <!-- 评论人 -->
                    <div class="from-whom" @click="tochat(comment.business.id)">
                      <div class="avatar">
                        <img :src="comment.business.avatar_text" />
                      </div>
                      <div class="name">{{comment.business.nickname}}</div>
                    </div>

                    <!-- 评论内容 -->
                    <div class="review-details">
                      <div class="content">评论内容</div>
                      <div>
                          <img :src="thumb" v-if="comment.thumbs" v-for="(thumb,index) in comment.thumbs.split('|')" :key="index" />
                      </div>
                      <div class="time">{{comment.comdate}}</div>
                      <van-rate v-model="comment.rate" readonly />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </van-list>
    </van-pull-refresh>

    <van-back-top bottom="15vh" />
    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
      <div class="ProductTip">
        三、我们如何使用信息 <br />
        四、我们如何共享信息<br />
        五、我们如何转让信息<br />
        六、我们如何公开披露信息<br />
        七、一般储存期限<br />
        八、我们如何确保您的信息安全<br />
        九、您能做什么<br />
        十、我们如何处理未成年人的个人信息<br />
        十一、您的个人信息的存储地点<br />
        十二、本隐私权政策不适用的范围<br />
        十三、本隐私权政策如何更新<br />
        十四、联系我们<br />
      </div>
    </van-action-sheet>
    
    <van-sku
      v-model="SkuShow"
      :sku="sku"
      :initial-sku="initialSku"
      :goods="goods"
      :goods-id="product.id"
      :properties="properties"
      :quota="quota"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    >
    <template #sku-stepper>
      <div class="detailbox stepper">
        <span>购买数量：</span>
        <van-stepper v-model="nums" :max="sku.stock_num" :min="1"/>
      </div>
    </template>
    </van-sku>

    <!-- 底部导航栏 -->
    <van-action-bar placeholder>
      <van-action-bar-icon icon="chat-o" text="客服" to="/product/chat"/>
      <van-action-bar-icon icon="cart-o" text="购物车" to="/cart" v-if="!isLogin"/>
      <van-action-bar-icon icon="cart-o" text="购物车" to="/cart"  :badge="cartNum" v-else/>
      <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" v-if="isCollection" @click="collection(false)"/>
      <van-action-bar-icon icon="star-o" text="收藏" v-else @click="collection(true)"/>
      <van-action-bar-button type="danger" text="立即购买" @click="SkuShow=true" />
    </van-action-bar>
</template>

<script setup>
import { getCurrentInstance, onBeforeMount, reactive, ref } from "vue"

//选项卡
let TabActive = ref(0)
let rate = ref(4.5)

//条款服务
let TipShow = ref(false)
//规格
let SkuShow = ref(false)

const {proxy} = getCurrentInstance()
let product = ref({})
let id = proxy.$route.query.id

import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'
let sku = ref({
  tree: [],
  list: [],
  price: 0, // 默认价格（单位元）
  stock_num: 0, // 商品总库存
  })
let properties = ref([])
let quota = ref(0);
let goods = ref({
  // 默认商品 sku 缩略图
  picture: '',
})
let initialSku = reactive({
  // 初始选中的商品属性
  // 键：属性id
  // 值：属性值id列表
  selectedProp: {}
})


let isLogin = ref(proxy.$business.value.id != 0)
let isCollection = ref(false)
let cartNum = ref(0)
onBeforeMount(async ()=>{
  //产品详情
  let result = await proxy.$GET({
    url:'/product/info',
    params:{id}
  })
  if(result.code){
    product.value = result.data
    goods.value.picture = result.data.thumbs_text
    sku.value.price = result.data.price
    sku.value.stock_num = result.data.stock
  }else{
    showFailToast({
      message: result.msg,
      duration: 1000,
      onClose: () => proxy.$router.push('/product/comment')
    })
  }
  //规格
  result = await proxy.$GET({
    url:'/product/prop',
    params:{id}
  })
  result.forEach(e => {
    let isinclude = false
    properties.value.forEach(p => {
      if(p.k_id==e.propid){
        isinclude = true
        p.v.push({
            id: e.id, // 属性值id
            name: e.value, // 属性值名
            price: parseFloat(e.price)*100, // 属性值加价
            text_status: 1, // 属性启用/禁用状态 0 - 禁用，1 - 启用
          })
        return
      }
    })
    if(!isinclude){
      properties.value.push({
        k_id: e.propid, // 属性id
        k: e.prop_text, // 属性名
        is_multiple: false, // 是否可多选
        v: [{
            id: e.id, // 属性值id
            name: e.value, // 属性值名
            price: parseFloat(e.price)*100, // 属性值加价
            text_status: 1, // 属性启用/禁用状态 0 - 禁用，1 - 启用
          }],
      })
      sku.value.list.push({
        s1 : e.propid,
        price : parseFloat(product.value.price)*100, //默认的商品价格
        stock_num : product.value.stock,
      })
      initialSku.selectedProp[e.propid] = [e.id]
    }
  })
  // console.log(sku.value)
  // console.log(properties.value)
  //登录状态
  if(!isLogin.value){
    const token = localStorage.getItem('token')
    if(token){
        const result = await proxy.$GET({
            url:'/business/check',
            params:{token}
        })
        if(result.code==0){
          isLogin.value = false
        }else{
          proxy.$business.value = result.data;
          isLogin.value = true
        }
    }else{
      isLogin.value = false
    }
  }
  //收藏初始化
  if(isLogin.value)
  {
    result = await proxy.$GET({
      url:'/product/collection',
      params:{id}
    })
    isCollection.value = result
    result = await proxy.$GET({
      url:'/product/cart',
      params:{type:'num'}
    })
    cartNum.value = result
  }
});

//收藏
const collection = async (change)=>{
  let result = await proxy.$PUT({
    url:'/product/collection',
    params:{id},
    data:{change}
  })
  if(result.code==404){
    showFailToast({
        message: '未登录',
        duration: 1000,
        onClose: () => proxy.$router.push({path:'/business/login',query:{path:'/product/info',query:JSON.stringify({id})}})
    })
  }else{
    if(result.code){
      showSuccessToast({
        message: result.msg,
        duration: 1000,
      })
      isCollection.value = change
    }else{
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }
  }
}

let page = ref(1)
let commentList = ref([])
let finished = ref(false) //是否无更多数据
let refreshing = ref(false) //下拉刷新
let loading = ref(false)
let error = ref(false)
//下拉刷新
const refresh = async () =>
{
  if(TabActive.value==0)return
  refreshing.value = true
  //可以去掉定时器
    //清空查询参数
    page.value = 1
    commentList.value = []
    finished.value = false
    loading.value = true

    //加载数据方法
    load()
}

//加载数据方法
const load = async () =>
{
  if(TabActive.value==0){
    refreshing.value = false
    loading.value = false
    finished.value = false
    return
  }
  let result = await proxy.$GET({
    url:'/product/comment',
    params:{
      id,
      pageSize:6,
      page:page.value,
    }
  })
  if(result)
  {
    commentList.value = commentList.value.concat(result.data)
    refreshing.value = false
    loading.value = false
    finished.value = !result.has_more
    if(result.has_more)  page.value++
  }

  //请求发送完毕后，加载状态也就完毕了

  //如果没有更多数据了 就说明已经加载到底了....
}
watch(TabActive,(newVal)=>{
  newVal?refresh():(commentList.value=[])
})

//添加购物车
const nums = ref(1)
let onAddCartClicked = async (skuData,jump=false)=>{
  let skuComb = skuData.selectedSkuComb
  if(skuComb){
    let result = await proxy.$PUT({
      url:'/product/cart',
      params:{id},
      data:{
        nums:nums.value,
        price:(skuComb.property_price+skuComb.price)/100,
        attrs:JSON.stringify(skuComb.properties.map(p=>p.v[0].id))
      }
    })
    if(result){
      if(jump){
        proxy.$router.push('/cart')
      }
      SkuShow.value = false
      showSuccessToast({
        message: result.msg,
        duration: 1000,
      })
    }else{
      SkuShow.value = false
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }
  }else{
    showFailToast({
      message: '请选择商品规格',
      duration: 1000,
    })
  }
}
//购买
let onBuyClicked = async (skuData)=>{
  onAddCartClicked(skuData,true)
}

const tochat = (receiveid)=>{
  if(isLogin&&receiveid!=proxy.$business.value.id){
      proxy.$router.push(`/product/chat?receiveid=${receiveid}`)
  }
}
</script>
<style scoped>
@import url('/assets/css/ProductInfo.css');
.stepper{
  display: flex;
  justify-content:space-between;
}
</style>